<template>
  <div style="padding-bottom: 60px;">
    <Anchor :labelList="labels" :labelWidth="100">
      <div id="row-02" class="line">
        <BreakSpace label="选择盘点仓库" :containerStyle="{ marginBottom: '10px' }"></BreakSpace>
        <el-card class="box-card" shadow="never" :body-style="{ padding: '10px 5px' }">
          <!-- <div slot="header" class="clearfix">
        <span>选择盘点仓库</span>
          </div>-->
          <FilterTable
            ref="table"
            columnsRef="partAccessAccessInventoryAddPanel"
            height="170"
            :columns="columns"
            :dataSource="dataSource"
            :onColumnsChange="columns => (this.columns = columns)"
            :onRowSelectChange="
              rows => {
                this.selectRows = rows;
              }
            "
          ></FilterTable>
        </el-card>
      </div>
      <!-- <div :style="{ height: '20px' }"></div> -->
      <div id="row-03" class="line">
        <BreakSpace label="操作条件" :containerStyle="{ marginTop: '10px', marginBottom: '10px' }"></BreakSpace>
        <el-card class="box-card" shadow="never" :body-style="{ padding: '10px 5px' }">
          <!-- <div slot="header" class="clearfix">
            <span>操作条件</span>
          </div>-->
          <FormPanel ref="form" :labelWidth="100" :cols="3" :list="list" :isSubmitBtn="false"></FormPanel>
        </el-card>
      </div>
    </Anchor>
    <div
      :style="{
        position: 'absolute',
        left: 0,
        bottom: 0,
        right: 0,
        zIndex: 9,
        borderTop: '1px solid #e9e9e9',
        padding: '10px 20px',
        background: '#fff',
        textAlign: 'right'
      }"
    >
      <AjaxButton size="small" type="primary" :disabled="false" :click="createNewOrderBtnClick">生成空盘点单号</AjaxButton>
      <AjaxButton
        size="small"
        :disabled="false"
        :click="
          () => {
            this.$emit('cancel');
          }
        "
        >关闭</AjaxButton
      >
      <AjaxButton size="small" type="primary" :disabled="isConfirmShow" :click="confirmBtnClick">保存</AjaxButton>
    </div>
  </div>
</template>
<script>
import { state, mutations } from './store';
import { dictionary } from '@/utils/dictMixin';
import { saveBlankInventoryNo, findStorageCode, addNewInventoryNo, querypartGroupCodes } from '@/api/part/access/accessInventory/index.js';
import { getSeries } from '@/api/customerRepair/customerCare/insuranceDueRemind/index';
import { getSeriesData, getBrandList } from '@/api/common/cars/brandcarsModels';
import { getBrand } from '@/api/repair/basicParameters';

export default {
  name: 'access-addpanel',
  mixins: [dictionary],
  props: {
    ptype: String // 模块
  },
  data() {
    return {
      list: this.createList(),
      labels: this.createAnchorLabels(),
      loading: false,
      columns: this.createColumns(),
      dataSource: [],
      selectRows: [],
      isConfirmShow: false,
      SeriesData: []
    };
  },
  mounted() {
    window.pjpd_add = this;
    // this.initDict();
    // 查询仓库
    this.queryStorage();
  },
  methods: {
    createColumns() {
      return [
        {
          title: '序号',
          dataIndex: 'index',
          width: 100,
          sorter: true,
          filter: true,
          filterType: 'input',
          render: props => {
            return <span>{props.row.$index + 1}</span>;
          }
        },
        {
          title: '仓库代码',
          dataIndex: 'STORAGE_CODE',
          filter: true,
          filterType: 'input',
          sorter: true
        },
        {
          title: '仓库名称',
          dataIndex: 'STORAGE_NAME',
          filter: true,
          filterType: 'input',
          sorter: true
        }
      ];
    },
    createList() {
      return [
        {
          type: 'SELECT',
          label: '排序方式',
          fieldName: 'sortBy',
          initialValue: '1',
          itemList: [
            {
              text: '仓库+库位',
              value: '1'
            },
            {
              text: '仓库+配件代码',
              value: '2'
            },
            {
              text: '仓库+配件名称',
              value: '3'
            }
            // ,
            // {
            //   text: '仓库+车型',
            //   value: '4'
            // }
          ]
        },
        {
          type: 'SELECT',
          label: '库存情况',
          fieldName: 'amount',
          initialValue: '',
          itemList: this.createDictList(1308)
        },
        // {
        //   type: 'SELECT',
        //   label: '车系',
        //   fieldName: 'group',
        //   initialValue: '',
        //   itemList: []
        // },
        {
          type: 'SELECT',
          label: '停用',
          fieldName: 'stop',
          initialValue: '',
          itemList: this.createDictList(1004)
        },
        {
          type: 'INPUT_NUMBER',
          label: '每张盘点单数量',
          fieldName: 'count',
          initialValue: 1000,
          min: 100,
          precision: 0
        },
        // {
        //   type: 'INPUT',
        //   label: '库位',
        //   fieldName: 'storagePositionCode',
        //   initialValue: ''
        //   // min: 100,
        //   // precision: 0
        // },
        {
          type: 'CHECKBOX',
          label: '是否锁定库存',
          fieldName: 'isLock',
          hidden: true,
          initialValue: 10041002,
          options: { trueValue: 10041001, falseValue: 10041002 }
          // min: 100,
          // precision: 0
        },
        {
          type: 'SELECT',
          label: '盘点类型',
          fieldName: 'orderStatus',
          initialValue: '',
          rules: [{ required: true, message: '请选择', trigger: 'blur' }],
          itemList: this.createDictList(9195)
        }
        // {
        //   type: 'INPUT',
        //   label: '配件代码',
        //   fieldName: 'partNo',
        //   initialValue: ''
        //   // min: 100,
        //   // precision: 0
        // }
      ];
    },
    createAnchorLabels() {
      return [
        {
          title: '选择盘点仓库',
          id: 'row-02'
        },
        {
          title: '操作条件',
          id: 'row-03'
        }
      ];
    },
    // 查询仓库列表
    async queryStorage() {
      this.$refs.table.START_LOADING();
      const findStorageCodeRes = await findStorageCode();
      this.$refs.table.STOP_LOADING();
      console.log('findStorageCode', findStorageCodeRes);
      this.dataSource = findStorageCodeRes.data;
    },
    // 生成空盘点单
    async createNewOrderBtnClick() {
      this.saveBlankInventoryNoRes();
    },
    // 确定按钮
    async confirmBtnClick() {
      this.START_LOADING();
      const [err, formP] = await this.$refs.form.GET_FORM_DATA();
      console.log('save:::', formP);
      if (err) {
        console.error(err);
        return;
      }
      formP.remark = '';
      if (formP.sortBy !== '') {
        switch (formP.sortBy) {
          case '1':
            formP.remark += '排序方式：仓库+库位；';
            break;
          case '2':
            formP.remark += '排序方式：仓库+配件代码；';
            break;
          case '3':
            formP.remark += '排序方式：仓库+配件名称；';
            break;
          case '4':
            formP.remark += '排序方式：仓库+车型；';
            break;
          default:
            break;
        }
      }
      if (formP.amount !== '') {
        formP.remark += '库存情况：' + this.createDictText(formP.amount, '1308') + ';';
      }
      if (formP.group !== '') {
        // formP.remark += '车系：' + this.getSeriesName(formP.group) + ';';
      }
      if (formP.stop !== '') {
        formP.remark += '停用状态：' + this.createDictText(formP.stop, '1004') + ';';
      }
      if (formP.count !== '') {
        formP.remark += '每张盘点单配件个数：' + formP.count + ';';
      }
      // if (formP.storagePositionCode !== '') {
      //   formP.remark += '库位: ' + formP.storagePositionCode + ';';
      // }
      // if (formP.partNo !== '') {
      //   formP.remark += '配件代码: ' + formP.partNo + ';';
      // }
      if (formP.isLock) {
        formP.remark += '是否锁定库存: ' + (formP.isLock == 10041002 ? '否' : '是') + ';';
      }

      // 增加storage列表
      formP.storages = [];
      this.selectRows.map(e => {
        formP.storages.push(e.STORAGE_CODE);
      });
      // console.log(formP, '表单对象');
      // console.log(formP, '表单对象', JSON.stringify(formP));
      // 模块区分
      if (this.ptype) {
        formP.ptype = this.ptype;
      }
      formP.dms_search = this.dataSource.map(item => {
        const flagItem = this.selectRows.find(x => x._uid === item._uid);
        if (flagItem) {
          const _flagItem = Object.assign({}, flagItem);
          _flagItem.checkedId = 'on';
          return _flagItem;
        } else {
          return item;
        }
      });
      this.isConfirmShow = true;
      const res = await addNewInventoryNo(formP);
      if (res.resultCode == 400) {
        this.isConfirmShow = false;
        return;
      }
      console.log('新建配件盘点 确认', res);
      this.$emit('confirm', res.data);
      this.STOP_LOADING();
    },
    // 生成盘点单号
    async saveBlankInventoryNoRes() {
      const [err, formP] = await this.$refs.form.GET_FORM_DATA();
      if (err) {
        console.error(err);
        return;
      }
      console.log('new:::', formP);
      formP.remark = '';
      if (formP.sortBy !== '') {
        switch (formP.sortBy) {
          case '1':
            formP.remark += '排序方式：仓库+库位；';
            break;
          case '2':
            formP.remark += '排序方式：仓库+配件代码；';
            break;
          case '3':
            formP.remark += '排序方式：仓库+配件名称；';
            break;
          case '4':
            formP.remark += '排序方式：仓库+车型；';
            break;
          default:
            break;
        }
      }
      if (formP.amount !== '') {
        formP.remark += '库存情况：' + this.createDictText(formP.amount, '1308') + ';';
      }
      if (formP.group !== '') {
        // formP.remark += '车系：' + this.getSeriesName(formP.group) + ';';
      }
      if (formP.stop !== '') {
        formP.remark += '停用状态：' + this.createDictText(formP.stop, '1004') + ';';
      }
      if (formP.count !== '') {
        formP.remark += '每张盘点单配件个数：' + formP.count + ';';
      }
      // if (formP.storagePositionCode) {
      //   formP.remark += '库位: ' + formP.storagePositionCode + ';';
      // }
      // if (formP.partNo) {
      //   formP.remark += '配件代码: ' + formP.partNo + ';';
      // }
      if (formP.isLock) {
        formP.remark += '是否锁定库存: ' + (formP.isLock == 10041002 ? '否' : '是') + ';';
      }
      // 增加storage列表
      formP.storages = [];
      this.selectRows.map(e => {
        formP.storages.push(e.STORAGE_CODE);
      });
      // console.log(formP, '表单对象');
      // console.log(formP, '表单对象', JSON.stringify(formP));
      // 模块区分
      if (this.ptype) {
        formP.ptype = this.ptype;
      }
      formP.dms_search = this.dataSource.map(item => {
        const flagItem = this.selectRows.find(x => x._uid === item._uid);
        if (flagItem) {
          const _flagItem = Object.assign({}, flagItem);
          _flagItem.checkedId = 'on';
          return _flagItem;
        } else {
          return item;
        }
      });
      const saveBlankInventoryNoRes = await saveBlankInventoryNo(formP);
      console.log('saveBlankInventoryNo', saveBlankInventoryNoRes);
      // const { inventory_no, handler, inventory_date } = saveBlankInventoryNoRes.data;
      // // this.$emit('setListData', { inventory_no, handler, inventory_date });
      saveBlankInventoryNoRes.data.isBlank = 'isBlank';
      this.$emit('confirm', saveBlankInventoryNoRes.data);
      // mutations.setState({ inventory_no, handler, inventory_date });
      /**
       * INVENTORY_NO 盘点单号
       * HANDLER 经手人name
       * HANDLERH 经手人(隐藏域code)
       * INVENTORY_DATE 盘点日期
       * INVENTORY_DATE2 (new Date(t).Format('yyyy-MM-dd hh:mm:ss');
       * REMARK
       */
    },
    // 初始化字典
    async initDict() {
      // const CheXingZu = await querypartGroupCodes();
      // const CheXingZu = await getSeries();
      let brandId = 0;
      let res = await getBrand();
      if (res.resultCode == 200) {
        brandId = res.data[0].BRAND_ID;
      }

      const CheXingZu = await getSeriesData(brandId);
      this.list.find(x => x.fieldName === 'group').itemList = CheXingZu.data.map(x => ({ text: x.seriesName, value: x.seriesId }));
      this.SeriesData = CheXingZu.data.map(x => ({ text: x.seriesName, value: x.seriesId }));
    },
    START_LOADING() {
      this.loading = true;
    },
    STOP_LOADING() {
      this.loading = false;
    },
    getSeriesName(SERIES_ID) {
      const item = this.SeriesData.find(x => {
        return x.value == SERIES_ID;
      });
      return item ? item.text : '';
    }
  }
};
</script>
<style scoped>
.btn-wrap {
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  height: 60px;
  display: flex;
  justify-content: center;
  align-items: center;
  background-color: #ffffff;
  border-top: 1px solid #d7dae2;
  z-index: 10000;
}
</style>
